var CONSTS = '../consts';
var logger = '../models/logger';

var EARTH_RADIUS = 6378137.0; //单位:米
var PI = Math.PI;

var locationHelper = {
    getBaiduAk: function() {
        var e = [CONSTS.BAIDU.APPTOKEN];//["snflL5Ml01VAfX4s3Cj9cY5P", "j8moP97IUEfnaHhwNpFw9lBp", "xYg7sBnoeC48jKUZkvcH0639", "qwZ9oLUvSnixC7UoBntpFXmd", "ICuEGrsHdhqrmBQsuK1ma98D", "Oq1helNPvzN3SH7YV6faU3Lb", "fL5VvnqPDWnKwDOQYKbyOunu", "ylTiLe9kVVp9uBaIHibYl8av", "epx2GlGrgjgEizwW8iYsHwQZ"];
        return e[parseInt(Math.random() * e.length)];
    },

    getAddressInfoByPoint: function(latitude, longitude, isPois, callback) {
        var request = require('request');
        var url = 'http://api.map.baidu.com/geocoder/v2/?';
        logger.debug(url);

        url += 'ak=' + location.getBaiduAk();
        url += '&location=' + latitude + ',' + longitude;
        url += '&output=json';
        url += '&pois=' + (isPois ? 1 : 0);

        logger.debug('url:' + url);

        request.get(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                logger.debug(body);
                body = JSON.parse(body);
                0 == body.status ? callback && callback(body.result.addressComponent, body.result.pois) : (callback && callback(null))
            }
        });
    },

    getPointByAddress: function(city, address, callback) {
        var request = require('request');
        var url = 'http://api.map.baidu.com/geocoder/v2/?';
        logger.debug(url);

        url += 'ak=' + location.getBaiduAk();
        if(city && city.length>0){
            url +=  '&city=' + encodeURIComponent(city);
        }
        url += '&address=' + encodeURIComponent(address);
        url += '&output=json';
        logger.debug('url:' + url);
        request.get(url, function (error, response, body) {
            logger.debug(error);
            logger.debug(response.statusCode)
            logger.debug(body);

            if (!error && response.statusCode == 200) {
                logger.debug(body);
                body = JSON.parse(body);
                0 == body.status ? callback && callback(body.result.location) : (callback && callback(null))
            }
        });
    },

    getDistanceOfTwoPoints: function(point1, point2){  
        var EARTHRADIUS = 6370996.81;   
        /** 
         * 将度转化为弧度 
         * @param {degree} Number 度      
         * @returns {Number} 弧度 
         */  
        var degreeToRad =  function(degree) {  
            return Math.PI * degree/180;      
        }  
          
        /** 
         * 将弧度转化为度 
         * @param {radian} Number 弧度      
         * @returns {Number} 度 
         */  
        var radToDegree = function(rad) {  
            return (180 * rad) / Math.PI;         
        }  
          
        /** 
         * 将v值限定在a,b之间，纬度使用 
         */  
        function _getRange(v, a, b) {  
            if (a != null) {  
                v = Math.max(v, a);  
            }  
            if (b != null) {  
                v = Math.min(v, b);  
            }  
            return v;  
        }  
          
        /** 
         * 将v值限定在a,b之间，经度使用 
         */  
        function _getLoop(v, a, b) {  
            while ( v > b) {  
              v -= b - a; 
            }  
            while (v < a) {  
              v += b - a;
            }  
            return v;  
        }  


        point1.lng = _getLoop(point1.lng, -180, 180);  
        point1.lat = _getRange(point1.lat, -74, 74);  
        point2.lng = _getLoop(point2.lng, -180, 180);       
        point2.lat = _getRange(point2.lat, -74, 74);  
          
        var x1, x2, y1, y2;  
        x1 = degreeToRad(point1.lng);  
        y1 = degreeToRad(point1.lat);  
        x2 = degreeToRad(point2.lng);  
        y2 = degreeToRad(point2.lat);  
  
        return EARTHRADIUS * Math.acos((Math.sin(y1) * Math.sin(y2) + Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1)));      
    }
}

module.exports = locationHelper;
